package global

import (
	"errors"
	"fmt"
	"github.com/sirupsen/logrus"
	"github.com/spf13/viper"
	"gorm.io/gorm"
	"hcy-api/lib/db"
	"hcy-api/structs/tables"
	"os"
)

var (
	LmsConf = new(LmsConfig)
	LmsLog  *logrus.Logger
	DB      *gorm.DB
)

type LmsConfig struct {
	ApiPort    int    `yaml:"apiPort"  json:"apiPort" mapstructure:"apiPort"`
	LogName    string `yaml:"logName" json:"logName" mapstructure:"logName"`
	LogLv      string `yaml:"logLv" json:"logLv" mapstructure:"logLv"`
	ShowSqlLog bool   `yaml:"showSqlLog" json:"showSqlLog"`
	Platform   string `yaml:"platform" json:"platform"` //平台根路由
	DB         string `yaml:"db" json:"DB"`             // 数据库类型

}

func InitLmsConfig(configName string) {
	v := viper.New()
	v.SetConfigType("yaml")
	v.SetConfigName(configName)
	v.AddConfigPath(".")
	err := v.ReadInConfig()
	if err != nil {
		fmt.Println(err)
	}
	err = v.Unmarshal(LmsConf)
	if err != nil {
		if errors.Is(err, os.ErrNotExist) {
			fmt.Println(err)
		}
	}
	if LmsConf.ApiPort == 0 {
		LmsConf.ApiPort = 9002
	}
	if LmsConf.DB == "" {
		LmsConf.DB = "sqlite"
	}
	if LmsConf.LogLv == "" {
		LmsConf.LogLv = "debug"
		LmsConf.ShowSqlLog = true
	}
	if LmsConf.LogName == "" {
		LmsConf.LogName = "lms.log"
	}

}

func InitDB() {
	dbSource := ""
	var err error
	switch LmsConf.DB {
	}
	DB, err = db.GetDB(LmsConf.DB, LmsConf.ShowSqlLog, dbSource, "")
	if err != nil {
		LmsLog.Error(err)
		return
	}
	if LmsConf.ShowSqlLog {

	}
	autoMigrate()
}

func autoMigrate() {
	type vector[T any] []T
	var li = vector[interface{}]{
		// lms
		&tables.Course{},
		&tables.CourseExtend{},
		&tables.CourseFolder{},
		&tables.Courseware{},
		&tables.CoursewareExtend{},
		&tables.CoursewareFolder{},
		&tables.ExamPapers{},
		&tables.MapExamQuestions{},
		&tables.Question{},
		&tables.ExamResult{},
		&tables.OptionExamResultLog{},
		&tables.MapCourseware{},
		&tables.QuestionFolder{},
		&tables.Knowledge{},
		&tables.MapKnowledgeDoc{},
		&tables.MapCourse2Org{},
		&tables.MapCourse2User{},
	}
	for _, item := range li {
		if !DB.Migrator().HasTable(item) {
			err := DB.AutoMigrate(item)
			if err != nil {
				LmsLog.Error(fmt.Errorf("初始化数据库表结构异常: %v", err.Error()))
			}
		}
	}
	initCoursewareFolderRoot()
	initCourseFolderRoot()
}
